package com.fivefu.core.data.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.data.constant.PlatformEnum;
import com.fivefu.core.data.entity.DbFfskyeyePlatform;
import com.fivefu.core.data.entity.DbFfskyeyeRegion;
import com.fivefu.core.data.mapper.DbFfskyeyeRegionMapper;
import com.fivefu.core.data.services.DbFfskyeyePlatformService;
import com.fivefu.core.data.services.DbFfskyeyeRegionService;
import com.fivefu.core.hik.entity.DbHikRegions;
import com.fivefu.core.hik.services.DbHikRegionsService;
import com.fivefu.core.hillstone.entity.DbHillstoneOrganization;
import com.fivefu.core.hillstone.services.DbHillstoneOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 域 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-09-01 11:12:00
 */
@Service
public class DbFfskyeyeRegionServiceImpl extends ServiceImpl<DbFfskyeyeRegionMapper, DbFfskyeyeRegion> implements DbFfskyeyeRegionService {

    @Autowired
    private DbHillstoneOrganizationService dbHillstoneOrganizationService;
    @Autowired
    private DbHikRegionsService dbHikRegionsService;
    @Autowired
    private DbFfskyeyePlatformService dbFfskyeyePlatformService;

    /**
     * 查询平台域数据集
     * @param platFormCode
     * @return
     */
    @Override
    public List<DbFfskyeyeRegion> queryPlatFormList(String platFormCode) {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (StrUtils.isNotNull(platFormCode)) {
            wrapper.eq("platform_code", platFormCode);
        }
        List<DbFfskyeyeRegion> regionList = baseMapper.selectList(wrapper);
        return regionList;
    }

    /**
     * 根据平台组织唯一编码及平台标记查询本地相关数据
     * @param code          平台组织唯一编码
     * @param platFormCode  平台标记
     * @return
     */
    @Override
    public DbFfskyeyeRegion queryRegion(String code,String platFormCode) {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("code",code);
        wrapper.eq("platform_code",platFormCode);
        DbFfskyeyeRegion region = baseMapper.selectOne(wrapper);
        return region;
    }

    /**
     * 编辑区域和组织架构信息
     * @param region
     * @param platFormCode
     */
    @Override
    public void editorOrganization(DbFfskyeyeRegion region,String platFormCode,String userId) {
        LocalDateTime time = LocalDateTime.now();
        DbFfskyeyeRegion oldRegion = queryRegion(region.getCode(),platFormCode);
        region.setUpdatedTime(time);
        region.setUpdatedBy(userId);

        if (null != oldRegion) {
            region.setId(oldRegion.getId());
            baseMapper.updateById(region);
        } else {
            region.setCreatedBy(userId);
            region.setCreatedTime(time);
            region.setIsDelete(0);
            baseMapper.insert(region);
        }
    }

    /**
     * 根据平台组织唯一编码查询本地相关数据集
     * @param code
     * @return
     */
    private List<DbFfskyeyeRegion> queryRegionList(String code) {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("code",code);
        List<DbFfskyeyeRegion> regionList = baseMapper.selectList(wrapper);
        return regionList;
    }

    /**
     * 查询汇总表中所有海康的数据集
     * @return
     */
    private List<String> queryHikList() {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("platform_code", PlatformEnum.HIKVERSION.getPlatformCode());
        List<DbFfskyeyeRegion> regionList = baseMapper.selectList(wrapper);
        List<String> resultList = regionList.stream().map(k -> k.getCode()).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 查询汇总表所有未删除域数据
     * @return
     */
    @Override
    public List<DbFfskyeyeRegion> queryAll() {
         QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<DbFfskyeyeRegion> regionList = baseMapper.selectList(wrapper);
        return regionList;
    }

    /**
     * 区域信息汇总入库
     * @param platformName  设备平台：海康，大华
     */
    @Override
    public void regionCollect(String platformName,String userId) {
        DbFfskyeyePlatform platform = dbFfskyeyePlatformService.queryPlatformByName(platformName);
        String platformCode = platformName;
        if (platform != null) {
            platformCode = platform.getPlatformCode();
        }
        List<DbFfskyeyeRegion> resultList = new ArrayList<>();

        if (PlatformEnum.HIKVERSION.getPlatformCode().equals(platformCode)) {
            //查询海康区域表数据
            List<DbHikRegions> regionsList = dbHikRegionsService.queryRegionList();
            if (null == regionsList || regionsList.size() <= 0) {
                return;
            }
            //转换海康区域表返回的数据信息
            resultList = formatHik(regionsList, platformCode);
        } else {
            //查询大华组织架构表数据
            List<DbHillstoneOrganization> organizationList = dbHillstoneOrganizationService.queryAll();
            if (null == organizationList || organizationList.size() <= 0) {
                return;
            }
            //转换大华组织架构表返回的数据信息
            resultList = formatHill(organizationList, platformCode);
        }

        List<String> codeList = resultList.stream().map(k -> k.getCode()).collect(Collectors.toList());

        for (DbFfskyeyeRegion region : resultList) {
            editorOrganization(region,platformCode,userId);
        }
        //删除多余的海康大华区域信息数据
        deleteCollectRegion(codeList,platformCode,userId);
        //统一处理数据库中所有与海康大华有关的数据信息更新parentid字段
        //先获取所有海康大华的数据信息集
        List<DbFfskyeyeRegion> regionList = queryPlatFormList(platformCode);
        updateCollectRegion(regionList,userId);
    }

    /**
     * 转换海康区域表返回的数据信息
     * @param list
     * @return
     */
    private List<DbFfskyeyeRegion> formatHik(List<DbHikRegions> list, String platformCode) {
        List<DbFfskyeyeRegion> resultList = new ArrayList<>();
        if (null == list || list.size() <= 0) {
            return resultList;
        }
        list.forEach(dbHikRegions -> {
            DbFfskyeyeRegion region = new DbFfskyeyeRegion();
            region.setCode(dbHikRegions.getIndexCode());
            region.setName(dbHikRegions.getName());
            if (StrUtils.isNotNull(dbHikRegions.getCatalogType())) {
                region.setType(dbHikRegions.getCatalogType());
            }
            if (StrUtils.isNotNull(dbHikRegions.getParentIndexCode())) {
                region.setParentCode(dbHikRegions.getParentIndexCode());
            }
            if (null != dbHikRegions.getSort()) {
                region.setSort(dbHikRegions.getSort());
            }
            if (StrUtils.isNotNull(dbHikRegions.getCascadeCode())) {
                region.setLevel(Integer.valueOf(dbHikRegions.getCascadeCode()));
            }
            region.setPlatformCode(platformCode);
            resultList.add(region);
        });
        return resultList;
    }

    /**
     * 删除多余的区域数据
     * @param codeList
     * @param platFormCode  平台标识
     */
    private void deleteCollectRegion(List<String> codeList, String platFormCode,String userId) {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (!codeList.isEmpty()) {
            wrapper.notIn("code",codeList);
        }
        wrapper.eq("platform_code",platFormCode);

        DbFfskyeyeRegion region = new DbFfskyeyeRegion();
        region.setIsDelete(1);
        region.setUpdatedTime(LocalDateTime.now());
        region.setUpdatedBy(userId);
        baseMapper.update(region,wrapper);
    }

    /**
     * 格式化大华组织架构表返回的数据信息
     * @param organizationList
     * @return
     */
    private List<DbFfskyeyeRegion> formatHill(List<DbHillstoneOrganization> organizationList, String platformCode) {
        List<DbFfskyeyeRegion> resultList = new ArrayList<>();
        if (null == organizationList || organizationList.size() <= 0) {
            return resultList;
        }

        organizationList.forEach(dbHillstoneOrganization -> {
            DbFfskyeyeRegion region = new DbFfskyeyeRegion();
            region.setCode(dbHillstoneOrganization.getOrgCode());
            region.setName(dbHillstoneOrganization.getName());
            if (StrUtils.isNotNull(dbHillstoneOrganization.getOrgType())) {
                region.setType(dbHillstoneOrganization.getOrgType());
            }
            if (StrUtils.isNotNull(dbHillstoneOrganization.getParentCode())) {
                region.setParentCode(dbHillstoneOrganization.getParentCode());
            }
            if (null != dbHillstoneOrganization.getSort()) {
                region.setSort(dbHillstoneOrganization.getSort());
            }
            if (StrUtils.isNotNull(dbHillstoneOrganization.getDomainId())) {
                region.setLevel(Integer.valueOf(dbHillstoneOrganization.getDomainId().toString()));
            }
            region.setPlatformCode(platformCode);
            resultList.add(region);
        });
        return resultList;
    }

    /**
     * 更新汇总域表中的parentid字段
     * @param regionList
     */
    private void updateCollectRegion(List<DbFfskyeyeRegion> regionList,String userId) {
        if (null == regionList || regionList.size() <= 0) {
            return;
        }
        regionList.forEach(region -> {
            //根据平台标识和平台父级组织唯一编码查询
            DbFfskyeyeRegion ffskyeyeRegion = queryRegion(region.getParentCode(),region.getPlatformCode());
            if (null != ffskyeyeRegion) {
                region.setParentid(ffskyeyeRegion.getId());
                region.setUpdatedBy(userId);
                baseMapper.updateById(region);
            }
        });
    }

    /**
     * 查询最大sort值
     * @param parentid 父级编号
     * @return
     */
    public Integer queryMaxSort(Long parentid){
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("parentid",parentid);
        wrapper.select("max(sort) as sort");
        DbFfskyeyeRegion region = baseMapper.selectOne(wrapper);
        return region.getSort();
    }

    /**
     * 编辑区域信息
     * @param region 区域信息
     * @param userid 操作用户编号
     */
    @Override
    public Long editRegionById(DbFfskyeyeRegion region, String userid){
        LocalDateTime time = LocalDateTime.now();
        region.setUpdatedBy(userid);
        region.setUpdatedTime(time);
        if (region.getId() != null){
            baseMapper.updateById(region);
        }else{
            region.setCode(UUID.randomUUID().toString());
            if (region.getParentid() != null){
                String pCode = null;
                Integer level = 1;
                Integer sort = 1;
                DbFfskyeyeRegion pRegion = getById(region.getParentid());
                if (pRegion != null){
                    pCode = pRegion.getParentCode();
                    level = pRegion.getLevel() + 1;
                    sort = queryMaxSort(region.getParentid());
                    if (sort == null){
                        sort = 0;
                    }
                    sort ++;
                }
                region.setParentCode(pCode);
                region.setLevel(level);
                region.setSort(sort);
            }

            region.setCreatedBy(userid);
            region.setCreatedTime(time);
            region.setIsDelete(0);
            baseMapper.insert(region);
        }
        return region.getId();
    }

    /**
     * 根据组织名称和层级查询相关信息
     * @param regionName   组织名称
     * @param pid   父级组织编号
     * @param id    组织编号
     * @return
     */
    @Override
    public DbFfskyeyeRegion queryRegionByRegionName(String regionName, String platform,Long pid,Long id) {
        QueryWrapper<DbFfskyeyeRegion> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (StrUtils.isNotNull(regionName)) {
            wrapper.eq("name",regionName);
        }
        if (StrUtils.isNotNull(platform)){
            wrapper.eq("platform_code", platform);
        }
        if (null != pid) {
            wrapper.eq("parentid",pid);
        }
        if (null != id) {
            wrapper.eq("id",id);
        }
        DbFfskyeyeRegion region = baseMapper.selectOne(wrapper);
        return region;
    }

    /**
     * 删除区域
     * @param regionId   区域编号
     * @param userId     操作用户编号
     */
    @Override
    public void deleteRegionById(Long regionId, String userId) {
        UpdateWrapper<DbFfskyeyeRegion> wrapper = new UpdateWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("id",regionId);

        wrapper.set("is_delete", 1);
        wrapper.set("updated_by", userId);
        wrapper.set("updated_time", LocalDateTime.now());
        baseMapper.update(null,wrapper);
    }
}
